import {asyncRouterMap} from '@/router'

export function inArray(arr, obj) {
  let i = arr.length
  while (i--) {
      if (arr[i] == obj) {
          return i
      }
  }
  return false
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles) {
  
  routes.forEach((item, index) => {
    if (item.hidden !== true && item.name) {
      if (inArray(roles, item.name) === false) {
        routes[index].hidden = true
      }
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRouter(item.children, roles)
      }
    }
  })

  return routes
}

const permission = {
  state: {
    routers: [],
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = routers
    }
  },
  actions: {
    GetRoutes({ commit }, data) {
      return new Promise(resolve => {
        let accessedRouters = filterAsyncRouter(asyncRouterMap, data)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
